# author: LiuShihao
# data: 2020/12/1 6:12 下午
# youknow: 各位老铁,我的这套代码曾经有人出价三个亿我没有卖,如今拿出来和大家分享,不求别的,只求大家免费的小红心帮忙点一点,这里谢过了。
# desc: 菜单
"""
打包
 pyinstaller -F -n SIS menu.py
"""
import os.path
filename = 'student.txt'

def main():
    while True:
        menu()
        choice =  int(input("请选择"))
        if choice in [1,2,3,4,5,6,7,0]:
            if choice == 0:
                answer = input("您确定要退出系统吗？y/n")
                if answer == 'y' or answer == 'Y':
                    print("谢谢您的使用！")
                    break # 退出系统
                else:
                    continue
            elif choice == 1:
                print("1.录入学生信息")
                insert()
            elif choice == 2:
                print("2.查找学生信息")
                search()
            elif choice == 3:
                print("3.删除学生信息")
                delete()
            elif choice == 4:
                print("4.修改学生信息")
                modify()
            elif choice == 5:
                print("5.排序")
                sort()
            elif choice == 6:
                print("6.统计学生总人数")
                total()
            elif choice == 7:
                print("7.显示所有学生信息")
                show()

def menu():
    print("========================学生信息管理系统==================================")
    print("---------------------------功能菜单-------------------------------------")
    print('\t\t\t\t\t1.录入学生信息')
    print('\t\t\t\t\t2.查找学生信息')
    print('\t\t\t\t\t3.删除学生信息')
    print('\t\t\t\t\t4.修改学生信息')
    print('\t\t\t\t\t5.排序')
    print('\t\t\t\t\t6.统计学生总人数')
    print('\t\t\t\t\t7.显示所有学生信息')
    print('\t\t\t\t\t0.退出系统')
    print("--------------------------------------------------------------------------")


def insert():
    student_list = []
    while True:
        id = int(input("请输入学号（如1001）"))
        if not id:
            break
        name = input("请输入学生姓名:")
        if not name:
            break
        try:
           english =  int(input("请输入英语成绩："))
           yuwen = int(input("请输入语文成绩："))
           math = int(input("请输入数学成绩："))
        except BaseException:
            print("输入无效，不是整数类型，请重新输入！")
            continue
        # 将录入的信息保存到字典当中
        student = {'id':id,'name':name,'english':english,'yuwen':yuwen,'math':math}
        student_list.append(student)
        answer = input("是否继续添加学生信息？y/n")
        if answer == 'y' or answer =='Y':
            continue
        else:
            break
    # 调用save()方法
    save(student_list)

def save(student_list):
    try:
        # a   是以追加打开文件，如果文件不存在，则创建文件，如果文件存在则文件末尾追加
        stu_txt = open(filename,'a',encoding='utf-8')
    except:
        # w是  已只写方式打开，如果文件不存在，则创建文件，如果文件存在则覆盖原有内容
        stu_txt = open(filename, 'w', encoding='utf-8')
    for item in student_list:
        stu_txt.write(str(item)+'\n')
    stu_txt.close()
# 查找
def search():
    student_query = []
    while True:
        id = ''
        name = ''
        if os.path.exists(filename):
            i= int(input('按学号查找请输入1,按姓名查找请输入2：'))
            if i==1 :
                id = int(input('请输入学生学号：'))
            elif i==2:
                name = input('请输入学生姓名：')
            else:
                print('请重新选择')
                # continue
                # 如果输错了 重新调用自己
                search()
            with open(filename,'r',encoding='utf-8') as rfile:
                student_old = rfile.readlines()
                for item in student_old:
                    d = dict(eval(str(item)))
                    if id != '':
                        if d['id'] == id:
                            student_query.append(d)
                    elif name != '':
                        if d['name'] == name:
                            student_query.append(d)
            # 显示查询结果
            show_student(student_query)
            # 清空列表
            student_query.clear()
            answer = input('是否要继续查询？y/n')
            if answer == 'y' or answer == 'Y':
                continue
            else:
                break
        else:
            print("未保存学生信息")
# 显示查询结果
def show_student(student_query):
    if len(student_query) == 0:
        print('没有查到结果!')
        return
    # 定义标题显示格式
    format_title = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}'
    print(format_title.format('学号','姓名','英语成绩','语文成绩','数学成绩','总成绩'))
    format_data = '{:^6}\t{:^12}\t{:^8}\t{:^12}\t{:^13}\t{:^8}'
    for item in student_query:
        print(format_data.format(item['id'],
                                 item['name'],
                                 item['english'],
                                 item['yuwen'],
                                 item['math'],
                                 int(item['english'])+int(item['yuwen'])+int(item['math'])))
# 删除
def delete():
    while True:
        student_id = int(input('请输入学生学号（如1001）'))
        if student_id != '':
            if os.path.exists(filename):
                # r 只读形式打开文件
                with open(filename,'r',encoding='utf-8') as file:
                    student_old = file.readlines()
            else:
                student_old = []
            flag = False   # 标记是否删除
            if student_old:  # student_old为空  布尔值为False   不为空才会执行if语句
                # w 只写   如果文件存在会覆盖原文件
                with open(filename,'w',encoding='utf-8') as wfile:
                    d = {}   #空字典
                    for item in student_old:
                        d = dict(eval(item))  # 将字符串转成字典
                        if d['id'] != student_id:
                            wfile.write(str(d)+'\n')   # 如果当前id不是要删除的id，将信息写入
                        else:
                            flag = True
                    if flag:
                        print("学号为{0}的学生信息已被删除！".format(student_id))
                    else:
                        print(f"没有找到学号为{student_id}的学生信息")
            else:
                # 磁盘上没有数据
                print("无学生信息")
            # 删除后重新显示所有学生信息
            show()
            answer = input("是否继续删除？y/n")
            if answer == 'y'or answer == 'Y':
                continue
            else:
                break
# 修改
def modify():
    show()
    if os.path.exists(filename):
        with open(filename,'r',encoding='utf-8') as rfile:
            student_old = rfile.readlines()
    else:
        return
    student_id = int(input("请输入要修改信息的学生的学号："))
    with open(filename,'w',encoding='utf-8') as wfile:
        for item in student_old:
            d =dict(eval(str(item))) # 将读取的每一行字符串装换成字典形式
            if d['id'] == student_id:
                print('找到学生信息，请重新录入学生信息：')
                while True:
                    try:
                        d['name'] = input('请输入学生姓名')
                        d['english'] = int(input('请重新输入学生英语成绩'))
                        d['yuwen'] = int(input('请重新输入学生语文成绩'))
                        d['math'] = int(input('请重新输入学生数学成绩'))
                    except:
                        print("输入格式不对，请重新输入")
                    else:
                        break
                wfile.write(str(d)+'\n')
                print("学生信息修改成功")
            else:
                print("未找到该学生信息！")
                wfile.write(str(d) + '\n')
        answer = input("是否继续修改其他学生信息？y/n")
        if answer == 'Y' or answer == 'y':
            modify() # 如果输入的是y，则继续递归调用方法，如果是n，则方法执行结束
# 排序
def sort():
    show()
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            student_list = rfile.readlines()
        student_new = []
        for item in student_list:
            d = dict(eval(item))
            student_new.append(d)
    else:
        print('未保存学生信息！')
        return
    ascOrDesc = int(input("请选择排序方式：0：升序 ，1：降序"))
    if ascOrDesc == 0 :
        ascOrDescBool = False
    elif ascOrDesc == 1 :
        ascOrDescBool = True
    else:
        print('输入的信息有误，请重新输入！')
        sort()
    mode = int(input("请输入排序凡方式：1：按英语成绩程序排序；2：按语文成绩排序；3：按数学成绩排序；4：按总成绩排序"))
    if mode == 1:
        student_new.sort(key=lambda x :int(x['english']),reverse=ascOrDescBool)
    elif mode == 2:
        student_new.sort(key=lambda x :int(x['yuwen']),reverse=ascOrDescBool)
    elif mode == 3:
        student_new.sort(key=lambda x :int(x['math']),reverse=ascOrDescBool)
    elif mode == 4:
        student_new.sort(key=lambda x :int(x['english'])+int(x['yuwen'])+int(x['math']),reverse=ascOrDescBool)
    else:
        print('输入的信息有误，请重新输入！')
        sort()
    show_student(student_new)

def total():
    if os.path.exists(filename):
        with open(filename,'r',encoding='utf-8') as rfile:
            student_list = rfile.readlines()
            if student_list:
                print(f"一共有{len(student_list)}位学生")
            else:
                print("没有学生信息！")
    else:
        print("未保存学生信息！")
def show():
    student_list = []
    if os.path.exists(filename):
        with open(filename,'r',encoding='utf-8') as rfile:
            students  = rfile.readlines()
        for item in students:
            student_list.append(eval(item))
        if student_list:
            show_student(student_list)
        else:
            print('没有学生信息！')
    else:
        print('未保存学生信息！')

if __name__ == '__main__':
    main()